# 1. 导入库
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score
from sklearn.preprocessing import LabelEncoder

# 1. 数据加载与探索（5）
df = pd.read_csv("house_rent.csv")
print(f"数据前5行：{df.head()}")   # (1)
print(f"数据形状{df.shape}")       # (1)
print(f"数据类型{df.dtypes}")      # (1)
# 缺失值处理
print("缺失值统计：\n", df.isnull().sum())  # (1)
df = df.dropna()                            # (1)

# 2. 特征工程（5）
le = LabelEncoder()                                 # (1)
df["floor_encoded"] = le.fit_transform(df["floor"])  # (1)

X = df[["area", "room_num", "living_room", "bathroom", "floor_encoded", "distance_sub"]] # (1)
y = df["rent"]                                                        # (1)
X_train, X_test, y_train, y_test = \
    train_test_split(X, y, test_size=0.3, random_state=2025)  # (1)

# 5. 建模与预测
print()
model = LinearRegression()  # (1)
model.fit(X_train, y_train)  # (1)
y_pred = model.predict(X_test)  # (1)

# 计算评估指标
mse = mean_squared_error(y_test, y_pred)   # (1)
r2 = r2_score(y_test, y_pred)              # (1)

print(f"均方误差（MSE）：{mse:.2f}") #(1)
print(f"决定系数（R²）：{r2:.2f}") #(1)


# 新数据预测
new_data = pd.DataFrame({
    "area": [85],
    "room_num": [2],
    "living_room": [1],
    "bathroom": [1],
    "floor_encoded": [le.transform(["中"])[0]],
    "distance_sub": [1.2]
})
pred_rent = model.predict(new_data)              # (1)
print(f"新房屋预测月租金：{pred_rent[0]:.2f}元")